package com.github.binarywang.demo.wx.mp.handler;

import com.github.binarywang.demo.wx.mp.builder.TextBuilder;
import com.github.binarywang.demo.wx.mp.config.CommonConstant;
import com.github.binarywang.demo.wx.mp.utils.StorageUtils;

import org.springframework.stereotype.Component;

import java.util.Map;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 * 
 * 用户扫描带场景值二维码时，可能推送以下两种事件：
 *
 * 如果用户还未关注公众号，则用户可以关注公众号，关注后微信会将带场景值关注事件推送给开发者。
 *
 * 如果用户已经关注公众号，在用户扫描后会自动进入会话，微信也会将带场景值扫描事件推送给开发者。{@link ScanHandler}
 */
@Component
public class SubscribeHandler extends AbstractHandler {

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context,
                                    WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());
        String qrsceneKey = StrUtil.replace(wxMessage.getEventKey(), "qrscene_", "");
        logger.info("带的场景sceneKey:{}", qrsceneKey);
        // 获取微信用户基本信息
        try {
            WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);
            if (userWxInfo != null) {
                // TODO 可以添加关注用户到本地数据库
            }
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 48001) {
                this.logger.info("该公众号没有获取用户信息权限！");
            }
        }


        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = this.handleSpecial(wxMessage, weixinService);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }

        try {
            return new TextBuilder().build("感谢关注,让我们一起好好学习,天天向上:\nhttps://gitee.com/anxiaole/DayDayUp", wxMessage, weixinService);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMpXmlMessage, WxMpService wxMpService) throws Exception {
        // 根据场景key,获取场景值
        String qrsceneKey = StrUtil.replace(wxMpXmlMessage.getEventKey(), "qrscene_", "");
        String sceneValue = StorageUtils.getStr(qrsceneKey);
        if (StrUtil.isNotEmpty(sceneValue)) {
            JSONObject entries = JSONUtil.parseObj(sceneValue);
            String url = entries.getStr("url");
            String appId = entries.getStr("appId");
            if (StrUtil.isNotEmpty(url) && StrUtil.isNotEmpty(appId)) {
                url = wxMpService.switchoverTo(appId).getOAuth2Service().buildAuthorizationUrl(url, CommonConstant.AUTH_USERINFO, "");
                return new TextBuilder().build(String.format("<a href=\"%s\">点击参加活动</a>", url), wxMpXmlMessage, wxMpService);
            }
        }
        return null;
    }

}
